const express = require("express");
const bodyParser = require("body-parser");
const app = express();

const models = require("../db/models");

// 专门处理 express.json()
app.use(express.json());
// 对 url 参数
app.use(express.urlencoded());
// 对 body 参数
app.use(bodyParser.urlencoded({ extended: true }));

// 1. 所有的错误，http status == 500


/** 创建一个todo */
app.post("/create", async (req, res, next) => {
  try {
    let { name, deadline, content } = req.body;
    let todo = await models.Todo.create({
      name,
      deadline,
      content
    });
    res.json({
      todo,
      message: "任务创建成功"
    });
  } catch (error) {
    next(error);
  }
  // let { name, deadline, content } = req.body;
  // res.json({
  //   todo: {},
  //   name,
  //   deadline,
  //   content
  // })
});

/** 修改一个todo */
app.post("/update", async (req, res, next) => {
  try {
    let { name, deadline, content, id } = req.body;
    let todo = await models.Todo.findOne({
      where: {
        id
      }
    });
    if (todo) {
      // 执行更新功能
      todo = await todo.update({
        name,
        deadline,
        content
      })
    }

    res.json({
      todo
    })
  } catch (error) {
    next(error);
  }

});

/** 修改 删除 一个todo任务状态 */
app.post("/update_status", async (req, res, next) => {
  try {
    let { id, status } = req.body;
    let todo = await models.Todo.findOne({
      where: {
        id
      }
    });
    if (todo && status != todo.status) {
      // 执行更新功能
      todo = await todo.update({
        status
      });
    }
    res.json({
      todo: todo
    })
  } catch (error) {
    next(error);
  }

});

/** 查询任务列表 */
app.get("/list/:status/:page", async (req, res, next) => {
  // 1. 状态 1：表示待办，2：表示完成，3：删除,-1全部
  // 2. 分页的处理
  try {
    let { status, page } = req.params;
    let limit = 10;
    let offset = (page - 1) * limit;
    let where = {};
    if (status != -1) {
     where.status = status;
    }
    let list = await models.Todo.findAndCountAll({
      where,
      offset,
      limit
    });
    res.json({
      list
    });
  } catch (error) {
    next(error);
  }
});

app.use((err, req, res, next) => {
  if (err) {
    res.status(500).json({
      message: err.message
    });
  }
});

app.listen(8080, () => {
  console.log("服务启动成功");
});